<?php
declare (strict_types=1);

namespace app\index;

use app\data\components\HtmlBuild;
use app\data\logic\FriendlinkLogic;
use app\data\logic\PageLogic;
use app\data\logic\SocialMediaLogic;
use think\App;
use think\exception\ValidateException;
use think\facade\Lang;
use think\facade\View;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * @var mixed
     */
    protected int $nav_id;
    /**
     * @var PageLogic
     */
    protected PageLogic $page;
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 渲染的页面
     * @var null
     */
    protected $fetchHtml = null;

    protected $page_id = null;

    /**
     * 临时存储菜单
     * @var array
     */
    protected $menus = [];

    /**
     * 解决方案列表
     * @var array
     */
    protected $cases = [];

    /**
     * 产品类型
     * @var array
     */
    protected $proCat = [];

    /**
     * 解决方案分类列表
     * @var array
     */
    protected $casesCat = [];

    /**
     * 新闻分类
     * @var array
     */
    protected $cmsCat = [];

    /**
     * 系统信息
     * @var array
     */
    protected $systemInfo = [];

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->nav_id = 0;
        // 控制器初始化
        $this->initialize();
        $this->page = new PageLogic();
        $friendlinksLogic = new FriendlinkLogic();
        $socialMediaLogic = new SocialMediaLogic();

        $action = $this->request->action();
        $navData = $this->page->getNavigateId($action);
        if (isset($navData['id']) && !empty($navData['id'])) {
            $this->nav_id = $navData['id'] ?? $this->page->getNavigateId('blog')['id'];
        }
        $this->menuList();

        $pageData = $this->page->getPageData($this->nav_id);
        if (isset($pageData['page_id'])) {
            $this->page_id = $pageData['page_id'];
        } else {
            $this->page_id = 0;
        }
        $pagePartList = $this->page->getPagePartList($this->page_id);
        View::assign('pagePartList', $pagePartList);
        View::assign('pageData', $pageData);
        View::assign('navData', $navData);

        // 获取当前页面的广告图
        $adData = $this->page->getAdData("*", [['page_id', '=', $this->page_id]]);
        View::assign('adData', $adData);

        // 获取系统配置项
        $extendConfigs = $this->page->getConfigList();
        $subConfigAry = array_column($extendConfigs, 'subConfig');
        $configs = [];
        for ($j = 0; $j < count($subConfigAry); $j++) {
            $configs = array_merge($configs, $subConfigAry[$j]);
        }
        $systemInfo = [];
        for ($i = 0; $i < count($configs); $i++) {
            $systemInfo[$configs[$i]['code']] = $configs[$i]['value'];
        }

        // 读取oss开关
        $oss = $this->page->getConfigDetailByCode('oss')['data'];
        View::assign('imgDomain', $oss['IS_ENABLED'] == 1 ? $oss['BIND_DOMAIN'] : "");

        $this->systemInfo = $systemInfo;
        View::assign('systemInfo', $systemInfo);

        // 获取底部页面
        $footerHtml = $this->page->getConfigDetailByCode('footer_html');
        View::assign('footerHtml', $footerHtml['data']['value']);

        // 站点列表
        $sites = $this->page->getCmsSitesList(['is_show' => 1]);
        View::assign('i18nSites', $sites['list']);
        // 挂件列表
//        $pendants = $this->page->getCmsPendantsList(['is_show' => 1]);
//        View::assign('pendants', $pendants['list']);

//        $this->cases = $this->page->getCaseList(['all' => 1]);
//        View::assign('cases', $this->cases);

        $this->proCat = $this->page->getProductsCategoryList(['all' => 1, 'is_show' => 1], 'id asc');
        View::assign('proCat', $this->proCat['list']);

        // 友链
        $friendlinks = $friendlinksLogic->getFriendlinkList(['all' => 1]);
        View::assign('friendlinks', $friendlinks);

        $this->casesCat = $this->page->getCaseCategoryList(['all' => 1,'is_show'=>1]);
        View::assign('casesCat', $this->casesCat);

        $this->cmsCat = $this->page->getCmsCatList(['all' => 1, 'is_show' => 1]);
        View::assign('cmsCat', $this->cmsCat);

        $socialMedias = $socialMediaLogic->getSocialMediaList(['all' => 1]);
        View::assign('socialMedias', $socialMedias);

        $pros = $this->page->getProductsList(['all' => 1, 'is_show' => 1]);
        View::assign('pros', $pros);

        $cases = $this->page->getCasesListByPages(1,10,1)['list'];
        View::assign('cases',$cases);

        $cmsList = $this->page->getArticleListByPages(1,5,null,['is_show'=>1]);
        View::assign('cmsList',$cmsList['list']);

        $proList = $this->page->getProductsList(['all'=>1,'is_show'=>1]);
        View::assign('proList',$proList);
    }

    // 初始化
    protected function initialize()
    {
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    public function menuList()
    {
        $menuList = $this->page->getIndexMenuList($this->request->action(), $this->request->url(), $this->nav_id);
        $this->menus = $menuList;
        View::assign('menuList', $menuList);
    }

    public function respMsg(int $code = 0, string $message = '', array $data = [], $count = ''): \think\response\Json
    {
        if ($count) {
            return json(['code' => $code, 'count' => $count, 'msg' => Lang::get($message), 'data' => $data], 200);
        } else {
            return json(['code' => $code, 'msg' => Lang::get($message), 'data' => $data], 200);
        }
    }

    /**
     * 返回加载的页面
     * @param string $html
     * @param int $page_type
     * @return string|null
     */
    public function responseFetchHtml(string $html = "", int $page_type = 0)
    {
        // 页面静态话处理


        $template = $html ?? $this->request->controller() . "/" . $this->request->action();

        $this->fetchHtml = View::fetch(strtolower($template));
        return $this->fetchHtml;
    }


}
